package com.campus.secondhand.controller;

import java.security.Principal;
import java.util.List;
import java.util.Map;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.campus.secondhand.common.Result;
import com.campus.secondhand.entity.User;
import com.campus.secondhand.model.dto.MessageSendDTO;
import com.campus.secondhand.model.dto.ProductMessageDTO;
import com.campus.secondhand.model.vo.ConversationVO;
import com.campus.secondhand.model.vo.MessageVO;

import com.campus.secondhand.service.MessageService;
import com.campus.secondhand.service.UserService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 消息控制器
 */
@RestController
@RequestMapping("/chat")
@RequiredArgsConstructor
@Slf4j
public class MessageController {

    private final MessageService messageService;
    private final UserService userService;

    /**
     * 获取会话的聊天消息
     * 
     * @param userId         用户ID
     * @param conversationId 会话ID
     * @param page           页码（可选，默认为1）
     * @param pageSize       每页数量（可选，默认为20）
     * @return 消息列表
     */
    @GetMapping("/messages")
    public Result<?> getChatMessages(
            @RequestParam Long userId,
            @RequestParam Long conversationId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {
        return messageService.getChatMessages(userId, conversationId, page, pageSize);
    }

    /**
     * 发送消息
     * 
     * @param messageSendDTO 消息发送DTO
     * @return 发送结果
     */
    @PostMapping("/send")
    public Result<MessageVO> sendMessage(@Validated @RequestBody MessageSendDTO messageSendDTO) {
        return messageService.sendMessage(messageSendDTO.getUserId(), messageSendDTO);
    }

    /**
     * 获取用户会话列表
     * 
     * @param userId   用户ID
     * @param page     页码（可选，默认为1）
     * @param pageSize 每页数量（可选，默认为20）
     * @return 会话列表
     */
    @GetMapping("/conversations")
    public Result<List<ConversationVO>> getUserConversations(
            @RequestParam Long userId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {
        return messageService.getUserConversationsPaged(userId, page, pageSize);
    }

    /**
     * 创建新会话
     * 
     * @param userId    发起方用户ID
     * @param partnerId 对话方用户ID
     * @return 创建的会话
     */
    @PostMapping("/create-conversation")
    public Result<ConversationVO> createConversation(
            @RequestParam Long userId,
            @RequestParam Long partnerId) {
        return messageService.createConversation(userId, partnerId);
    }

    /**
     * 删除会话
     * 
     * @param userId         当前用户ID
     * @param conversationId 会话ID
     * @return 操作结果
     */
    @DeleteMapping("/delete-conversation")
    public Result<Void> deleteConversation(
            @RequestParam Long userId,
            @RequestParam Long conversationId) {
        return messageService.deleteConversationById(userId, conversationId);
    }

    /**
     * 将指定用户在特定会话中的所有未读消息标记为已读
     * 
     * @param userId         用户ID
     * @param conversationId 会话ID
     * @return 操作结果
     */
    @PutMapping("/mark-read")
    public Result<Void> markConversationMessagesAsRead(
            @RequestParam Long userId,
            @RequestParam Long conversationId) {
        return messageService.markConversationMessagesAsRead(userId, conversationId);
    }

    // 以下是不符合新规范的方法，保留以确保兼容性，后续应移除

    @GetMapping("/with/{targetUserId}")
    @PreAuthorize("isAuthenticated()")
    public Result<List<MessageVO>> getConversationMessages(Principal principal, @PathVariable Long targetUserId) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return messageService.getConversationMessages(userId, targetUserId);
    }

    @GetMapping("/with/{targetUserId}/product/{productId}")
    @PreAuthorize("isAuthenticated()")
    public Result<List<MessageVO>> getConversationMessagesForProduct(
            Principal principal,
            @PathVariable Long targetUserId,
            @PathVariable Long productId) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return messageService.getConversationMessagesForProduct(userId, targetUserId, productId);
    }

    @PutMapping("/with/{targetUserId}/read")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> markConversationAsRead(Principal principal, @PathVariable Long targetUserId) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return messageService.markConversationAsRead(userId, targetUserId);
    }
}